package top.lileix.mybatis.generator.x.generator;

import java.io.IOException;
import java.util.Set;

import top.lileix.mybatis.generator.x.domain.Column;
import top.lileix.mybatis.generator.x.domain.Table;
import top.lileix.mybatis.generator.x.kit.FileKit;
import top.lileix.mybatis.generator.x.kit.NamingKit;

/**
 * 领域对象生成器
 * 
 * @author lilei
 *
 */
public class DomainGenerator implements Generator {

    private String packageName;// 包名
    private String outputDir;// 放代码的路径

    public DomainGenerator(String packageName, String outputDir) {
	super();
	this.packageName = packageName;
	this.outputDir = outputDir;
    }

    protected String packageTemplate = "package %s;%n%n";

    protected static String classDefineTemplate = "/**%n" + " power by lileix.top %n %s" + " */%n"
	    + "public class %s {%n%s}";

    @Override
    public String generatorStr(Table t) {
	StringBuilder ret = new StringBuilder();
	ret.append(String.format(packageTemplate, packageName));
	ret.append(String.format(classDefineTemplate, t.getRemark(), t.getModeName(),
		modelContent(t.getColumns())));
	return ret.toString();
    }

    @Override
    public boolean generatorFile(Table t) throws IOException {
	FileKit.wirtToFile(outputDir, t.getModeName() + ".java", generatorStr(t), true);
	return true;
    }

    protected static String filedTemplate = "\tprivate %s %s;%s%n%n";
    protected static String setterTemplate = "\tpublic void %s(%s %s) {%n" + "\t\t this.%s=%s;%n"
	    + "\t}%n%n";
    protected static String getterTemplate = "\tpublic %s %s() {%n" + "\t\treturn %s;%n"
	    + "\t}%n%n";

    public String modelContent(Set<Column> columns) {
	StringBuilder ret = new StringBuilder();
	for (Column column : columns) {
	    ret.append(String.format(filedTemplate, column.getFieldType(), column.getFieldName(),
		    column.getRemark() == null ? ""
			    : "".equals(column.getRemark()) ? "" : "//" + column.getRemark()));
	}
	for (Column column : columns) {
	    // 生成getter
	    String setterMethodName = "set" + NamingKit.firstCharToUpperCase(column.getFieldName());
	    String setter = String.format(setterTemplate, setterMethodName, column.getFieldType(),
		    column.getFieldName(), column.getFieldName(), column.getFieldName());
	    ret.append(setter);
	    // 生成setter
	    String getterMethodName = "get" + NamingKit.firstCharToUpperCase(column.getFieldName());
	    String getter = String.format(getterTemplate, column.getFieldType(), getterMethodName,
		    column.getFieldName());
	    ret.append(getter);
	}
	return ret.toString();
    }
}
